package com.timeshare.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.timeshare.dto.ReviewRequest;
import com.timeshare.entity.Appointment;
import com.timeshare.entity.Review;
import com.timeshare.entity.User;
import com.timeshare.mapper.AppointmentMapper;
import com.timeshare.mapper.ReviewMapper;
import com.timeshare.mapper.UserMapper;
import com.timeshare.service.ReviewService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 评价服务实现
 */
@Service
public class ReviewServiceImpl extends ServiceImpl<ReviewMapper, Review> implements ReviewService {
    
    private final AppointmentMapper appointmentMapper;
    private final UserMapper userMapper;
    
    public ReviewServiceImpl(AppointmentMapper appointmentMapper, UserMapper userMapper) {
        this.appointmentMapper = appointmentMapper;
        this.userMapper = userMapper;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createReview(Long userId, ReviewRequest request) {
        // 查询预约信息
        Appointment appointment = appointmentMapper.selectById(request.getAppointmentId());
        if (appointment == null) {
            throw new RuntimeException("预约不存在");
        }
        
        // 只能在已完成的预约上评价
        if (appointment.getStatus() != 3) {
            throw new RuntimeException("只能对已完成的预约进行评价");
        }
        
        // 确定被评价者
        Long reviewedId;
        if (appointment.getRequesterId().equals(userId)) {
            reviewedId = appointment.getProviderId();
        } else if (appointment.getProviderId().equals(userId)) {
            reviewedId = appointment.getRequesterId();
        } else {
            throw new RuntimeException("无权评价");
        }
        
        // 检查是否已评价
        LambdaQueryWrapper<Review> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Review::getAppointmentId, request.getAppointmentId())
               .eq(Review::getReviewerId, userId);
        if (this.count(wrapper) > 0) {
            throw new RuntimeException("已评价过此预约");
        }
        
        // 创建评价
        Review review = new Review();
        review.setAppointmentId(request.getAppointmentId());
        review.setReviewerId(userId);
        review.setReviewedId(reviewedId);
        review.setRating(request.getRating());
        review.setContent(request.getContent());
        review.setTags(request.getTags());
        
        this.save(review);
        
        // 更新被评价者的信誉分
        updateCreditScore(reviewedId);
    }
    
    @Override
    public Page<Review> getUserReviews(Long userId, Integer page, Integer size) {
        Page<Review> reviewPage = new Page<>(page, size);
        LambdaQueryWrapper<Review> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Review::getReviewedId, userId)
               .orderByDesc(Review::getCreateTime);
        return this.page(reviewPage, wrapper);
    }
    
    /**
     * 更新用户信誉分
     */
    private void updateCreditScore(Long userId) {
        // 查询用户所有评价
        LambdaQueryWrapper<Review> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Review::getReviewedId, userId);
        
        long count = this.count(wrapper);
        if (count == 0) {
            return;
        }
        
        // 计算平均评分
        double avgRating = this.list(wrapper).stream()
                .mapToInt(Review::getRating)
                .average()
                .orElse(5.0);
        
        // 转换为信誉分（1-5星映射到60-100分）
        int creditScore = (int) (60 + (avgRating - 1) * 10);
        
        // 更新用户信誉分
        User user = userMapper.selectById(userId);
        if (user != null) {
            user.setCreditScore(creditScore);
            userMapper.updateById(user);
        }
    }
}

